package cc.rengu.redp.flowable.bizmodel.metadata;

import cc.rengu.redp.flowable.bizmodel.db.domain.BizCfgModel;
import cc.rengu.redp.flowable.bizmodel.db.domain.BizData;
import cc.rengu.redp.flowable.bizmodel.db.domain.BizDict;
import cc.rengu.redp.flowable.bizmodel.web.service.BizCfgFieldService;
import cc.rengu.redp.flowable.bizmodel.web.service.BizDataService;
import cc.rengu.redp.flowable.bizmodel.web.service.BizDictService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BizDataDictHandler implements DictHandler {

    @Autowired
    BizDictService bizDictService;
    @Autowired
    BizDataService bizDataService;
    @Autowired
    BizCfgFieldService bizCfgFieldService;

    @Override
    public void create(String key, JSONObject srcJsonObj, BizCfgModel bizCfgModel) {
        bizCfgModel.getFieldData().forEach(bizCfgField ->{
            String fieldValue = srcJsonObj.getString(bizCfgField.getFieldName());
            if (bizCfgField.getIsDict() && StringUtils.isNotBlank(fieldValue)){
                BizDict bizDict = new BizDict();
                bizDict.setModelId(bizCfgModel.getModelId());
                bizDict.setFieldName(bizCfgField.getFieldName());
                bizDict.setDataUniqKey(key);
                bizDict.setFieldValue(fieldValue);
                bizDictService.save(bizDict);
            }
        });
    }

    @Override
    public List<BizDict> getDictList(String modelId, String fieldName) {
        //权限过滤（待实现）

        LambdaQueryWrapper<BizDict> lqwBd = new LambdaQueryWrapper();
        lqwBd.eq(BizDict::getModelId, modelId).eq(BizDict::getFieldName, fieldName).orderByDesc(BizDict::getBizDictId);
        return bizDictService.list(lqwBd);
    }

    @Override
    public String getDictDetail(String dataUniqKey) {
        //权限过滤（待实现）

        BizData bizData = bizDataService.getOneByUniqKey(dataUniqKey);
        if (bizData == null){
            return null;
        }

        if (bizData.getUniqKeyName() != null){
            JSONObject dataObj = JSONObject.parseObject(bizData.getData());
            dataObj.put(bizData.getUniqKeyName(), dataUniqKey);
            return dataObj.toJSONString();
        } else {
            return bizData.getData();
        }
    }
}
